﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using com.lover.common;
using System.IO;
using com.lover.astd.common.model;
using com.lover.common.http;

namespace com.lover.astd.common.partner.impl
{
    public class PpsLogin : LoginImplBase
    {
        public PpsLogin() : base() { }
        public override LoginResult login(ref List<Cookie> cookies, string verify_code = null, string extra = null)
        {
            LoginResult result = new LoginResult();

            logging();
            string loginurl = "http://game.pps.tv/passport/api/login?charset=gbk";
            _username = getGBKEscape(_acc.UserName);
            string data = String.Format("preurl=http%253A%252F%252Fgame.pps.tv%252Fastd_login.php%253F&position=website_138&username={0}&userpasswd={1}&captcha=", _username, _password);
            HttpResult resp = TransferMgr.doPostPure(loginurl, data, ref cookies, "http://game.pps.tv/astd_login.php?");
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }

            // must 302
            string location = resp.getExtraHeader("Location");
            if (location == null)
            {
                result.StatusCode = LoginStatusCode.FailInLogin;
                return result;
            }

            findingServerUrl();
            resp = TransferMgr.doGetPure(location, ref cookies);

            string content = resp.getContent(Encoding.GetEncoding("GBK"));
            // 首先查找游戏地址(登录后才有游戏地址)
            string gameString = String.Format("{0}服 ", _acc.ServerId);
            Regex re = new Regex(String.Format("<a.*href=\"([^\"']*?)\".*>{0}.*</a>", gameString));
            MatchCollection matches = re.Matches(content);
            if (matches == null || matches.Count == 0 || matches[0] == null) { result.StatusCode = LoginStatusCode.FailInFindingGameUrl; return result; }
            if (matches[0].Groups == null || matches[0].Groups.Count < 2) { result.StatusCode = LoginStatusCode.FailInFindingGameUrl; return result; }

            string redirecturl = matches[0].Groups[1].Value;

            processRedirect(redirecturl, result, ref cookies);
            return result;
        }
    }
}
